<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select
          class="main-select-tree filter-item"
          ref="selectTree"
          v-model="optionId"
          placeholder="设备位置"
          style="width: 320px;">
          <el-option v-for="item in formatData(factoryData)"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value" style="display: none;" />

          <el-tree class="main-select-el-tree" ref="selecteltree"
                   :data="factoryData"
                   node-key="id"
                   highlight-current
                   :props="defaultProps"
                   @node-click="handleNodeClick"
                   :expand-on-click-node="expandOnClickNode"
                   default-expand-all />

        </el-select>

        <el-input v-model="query.deviceCode" clearable placeholder="设备编码" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.deviceName" clearable placeholder="设备名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />

        <el-select v-model="query.alarmStatus" clearable filterable
                   placeholder="请选择" style="width: 185px;" class="filter-item" @change="crud.toQuery" >
          <el-option
                  v-for="item in dict.alarm_status"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value" />
        </el-select>

        <date-range-picker  class="date-item" v-model="query.createTime"></date-range-picker>

        <rrOperation :crud="crud"/>

      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="form.deviceCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="产线编码" prop="lineCode">
            <el-input v-model="form.lineCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="工段编码" prop="sectionCode">
            <el-input v-model="form.sectionCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="工位编码" prop="stationCode">
            <el-input v-model="form.stationCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="报警状态" prop="alarmStatus">
            <el-select v-model="form.alarmStatus" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.alarm_status"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="故障信息">
            <el-input v-model="form.alarmMsg" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="报警代码">
            <el-input v-model="form.alarmCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="开始报警时间">
            <el-date-picker v-model="form.startTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="结束报警时间">
            <el-date-picker v-model="form.endTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="耗时（分）">
            <el-input v-model="form.tripTime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="创建人">
            <el-input v-model="form.createBy" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-input v-model="form.createTime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="更新人">
            <el-input v-model="form.updateBy" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="更新时间">
            <el-input v-model="form.updateTime" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="deviceCode" label="设备编码" align="center" width="100px"/>
        <el-table-column prop="deviceName" label="设备名称" align="center" width="100px"/>
        <el-table-column prop="lineCode" label="产线编码" align="center" width="100px"/>
        <el-table-column prop="sectionCode" label="工段编码" align="center" width="100px"/>
        <el-table-column prop="stationCode" label="工位编码" align="center" width="100px"/>
        <el-table-column prop="alarmStatus" label="报警状态" align="center" width="100px">
          <template slot-scope="scope">
            <el-tag :type="getStatusColor(scope.row)">
              {{ dict.label.alarm_status[scope.row.alarmStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alarmMsg" label="故障信息" align="center" width="200px"/>
        <el-table-column prop="alarmCode" label="报警代码" align="center" width="200px"/>
        <el-table-column prop="startTime" label="开始报警时间" align="center" width="150px"/>
        <el-table-column prop="endTime" label="结束报警时间" align="center" width="150px"/>
        <el-table-column prop="tripTime" label="耗时（分）" align="center" width="100px"/>
        <el-table-column prop="createBy" label="创建人" align="center" width="100px"/>
        <el-table-column prop="createTime" label="创建时间" align="center" width="150px"/>
        <el-table-column prop="updateBy" label="更新人" align="center" width="100px"/>
        <el-table-column prop="updateTime" label="更新时间" align="center" width="150px"/>
<!--        <el-table-column v-if="checkPer(['admin','deviceAlarm:edit','deviceAlarm:del'])" fixed="right" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDeviceAlarm from '@/api/device/deviceAlarm'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import crudFactoryModel from "@/api/factory/factoryModel"

const defaultForm = { id: null, deviceCode: null, deviceName: null, lineCode: null, sectionCode: null, stationCode: null, alarmStatus: null, alarmMsg: null, alarmCode: null, startTime: null, endTime: null, tripTime: null, createBy: null, createTime: null, updateBy: null, updateTime: null }
export default {
  name: 'DeviceAlarm',
  components: { pagination, crudOperation, rrOperation, udOperation ,DateRangePicker},
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['alarm_status'],
  cruds() {
    return CRUD({ optShow: {
        add: false,
        edit: false,
        del: false,
        download: true,
        reset: true,
        import: false
      },title: '设备报警', url: 'api/deviceAlarm', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDeviceAlarm }})
  },
  data() {
    return {
      expandOnClickNode: true,
      options:[],
      optionId: '',
      factoryData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      lineCodes:[],
      sectionCodeList: [],
      stationCodeList: [],
      permission: {
        add: ['admin', 'deviceAlarm:add'],
        edit: ['admin', 'deviceAlarm:edit'],
        del: ['admin', 'deviceAlarm:del']
      },
      rules: {
        deviceCode: [
          { required: true, message: '设备编码不能为空', trigger: 'blur' }
        ],
        deviceName: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        lineCode: [
          { required: true, message: '产线编码不能为空', trigger: 'blur' }
        ],
        sectionCode: [
          { required: true, message: '工段编码不能为空', trigger: 'blur' }
        ],
        stationCode: [
          { required: true, message: '工位编码不能为空', trigger: 'blur' }
        ],
        alarmStatus: [
          { required: true, message: '报警状态不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'id', display_name: 'ID' },
        { key: 'deviceCode', display_name: '设备编码' },
        { key: 'deviceName', display_name: '设备名称' },
        { key: 'lineCode', display_name: '产线编码' },
        { key: 'sectionCode', display_name: '工段编码' },
        { key: 'stationCode', display_name: '工位编码' },
        { key: 'alarmStatus', display_name: '报警状态' },
        { key: 'alarmMsg', display_name: '故障信息' },
        { key: 'alarmCode', display_name: '报警代码' },
        { key: 'tripTime', display_name: '耗时（分）' },
        { key: 'createBy', display_name: '创建人' },
        { key: 'updateBy', display_name: '更新人' }
      ]
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    //重置之后
    [CRUD.HOOK.afterReset](crud) {
      this.optionId = '';
      return true
    },
    //初始化设备树
    initDeviceTree(){
      crudFactoryModel.getTreeNotDevice().then(res =>{
        this.factoryData = res;
      })
    },
    // 四级菜单
    formatData(data){
      let options = [];
      //递归解析
      this.pushOptions(options,data,'');
      this.options = options;
      return options;
    },
    //递归解析
    pushOptions(options,data,label){
      data.forEach((item,key) => {
        let name = label;
        if(name == ''){
          name = item.label;
        } else {
          name = name + "/" + item.label;
        }
        options.push({label:name,value:item.id});
        if(item.children){
          this.pushOptions(options,item.children,name);
        }
      });
    },
    handleNodeClick(node){
      this.optionId = node.id;
      this.options.forEach(item =>{
        if(item.value == node.id){
          this.query.place = item.label;
        }
      })
      this.$refs.selectTree.blur();
      this.crud.toQuery();
    },
    //加载产线模型
    async loadFactoryModel(level, pid) {
      const params = {
        modelType: level,
        pid: pid
      };
      return await crudFactoryModel.list(params).then(res => {
        let nodes = [];
        if (res) {
          res.forEach(item => {
            nodes.push({
              value: item.modelCode,
              label: item.modelName,
              leaf: level >= 2,
              id: item.id,
              type: item.modelType
            });
          })
        }
        return nodes;
      })
    },
    getStatusColor(item){
      if(item.alarmStatus == '0' ){
        return 'success';
      }else if(item.alarmStatus == '1'){
        return 'danger';
      }
    }
  },
  mounted() {
    //获取产线信息
    const root = this.loadFactoryModel(2);
    const lineCodes = [];
    root.then((result) => {
      if (result) {
        result.forEach(item => {
          lineCodes.push(item);
        })
      }
    })
    this.lineCodes = lineCodes;
    //获取工段信息
    const sectionCodeList = []
    const data1 = this.loadFactoryModel(3);
    data1.then((result) => {
      if (result) {
        result.forEach(item => {
          sectionCodeList.push(item);
        })
      }
    })
    this.sectionCodeList = sectionCodeList;
    //获取工位信息
    const stationCodeList = []
    const data2 = this.loadFactoryModel(4);
    data2.then((result) => {
      if (result) {
        result.forEach(item => {
          stationCodeList.push(item);
        })
      }
    })
    this.stationCodeList = stationCodeList;

    this.initDeviceTree();
  }
}
</script>

<style scoped>

</style>
